package com.example.project.controller;

import com.example.project.model.FAQ;
import com.example.project.service.FAQService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/faq")
public class FAQController {

    @Autowired
    private FAQService faqService;

    // 获取所有 FAQ
    @GetMapping
    public ResponseEntity<List<FAQ>> getAllFAQs() {
        List<FAQ> faqs = faqService.getAllFAQs();
        return ResponseEntity.ok(faqs);
    }

    // 根据 category_id 获取 FAQ 列表
    @GetMapping("/category/{categoryId}")
    public List<FAQ> getFAQsByCategoryId(@PathVariable int categoryId) {
        return faqService.getFAQsByCategoryId(categoryId);
    }

    // 添加 FAQ
    @PostMapping
    public ResponseEntity<String> addFAQ(@RequestBody FAQ faq) {
        // 验证 category_id 是否存在
        if (!faqService.categoryExists(faq.getCategoryId())) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("指定的 category_id 不存在");
        }

        FAQ savedFAQ = faqService.addFAQ(faq);
        if (savedFAQ != null) {
            return ResponseEntity.status(HttpStatus.CREATED).body("FAQ 添加成功");
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("FAQ 添加失败");
        }
    }

    // 更新 FAQ
    @PutMapping("/{id}")
    public ResponseEntity<String> updateFAQ(@PathVariable int id, @RequestBody FAQ faq) {
        boolean result = faqService.updateFAQ(id, faq);
        if (result) {
            return ResponseEntity.ok("FAQ 更新成功");
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("FAQ 更新失败：FAQ 未找到");
        }
    }

    // 删除 FAQ
    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteFAQ(@PathVariable int id) {
        boolean result = faqService.deleteFAQ(id);
        if (result) {
            return ResponseEntity.ok("FAQ 删除成功");
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("FAQ 删除失败：FAQ 未找到");
        }
    }

    // 根据搜索关键词获取 FAQ 列表
    @GetMapping("/search")
    public ResponseEntity<List<FAQ>> getFAQsBySearch(@RequestParam(required = false) String search) {
        List<FAQ> faqs;
        if (search != null && !search.isEmpty()) {
            faqs = faqService.getFAQsBySearch(search);
        } else {
            faqs = faqService.getAllFAQs();
        }
        return ResponseEntity.ok(faqs);
    }


}